//
//  AddCarVC.m
//  违章查询助手
//
//  Created by qianfeng on 15/10/27.
//  Copyright (c) 2015年 LY. All rights reserved.
//

#import "AddCarVC.h"
#import "ShowView.h"
#import "Car.h"
#import "showMessageVC.h"


extern NSInteger a;
extern int _myitem;
int add;

@interface AddCarVC ()<UITableViewDataSource,UITableViewDelegate,sucShowViewDelegate,ShowViewDelegate,UITextFieldDelegate,UIScrollViewDelegate>

@end

@implementation AddCarVC
{
    SucShowView * LookShowView;
    ShowView * _showView;
    UITableView * _tableView;
    int count;
    UIScrollView * _scroller;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    UITextField * textField = (id)[self.view viewWithTag:202];
    textField.text = _cityName;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createScroller];
    
    [self createTableView];
    
}


//创建scrollerView
-(void)createScroller
{
    _scroller = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, WIDTH, Height)];
    _scroller.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
    _scroller.contentSize = CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.height+200);
    _scroller.delegate = self;
    _scroller.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_scroller];
    
}


//创建tableView
-(void)createTableView
{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, Width, 380)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.scrollEnabled = NO;
    [_scroller addSubview:_tableView];
    
    UIButton * button = [[UIButton alloc]init];
    [button setTitle:@"开始查询" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button setBackgroundColor:[UIColor colorWithRed:1 green:0.5 blue:0.6 alpha:1]];
    button.layer.cornerRadius = 10;
    button.layer.masksToBounds = YES;
    [_scroller addSubview:button];
    [button addTarget:self action:@selector(equiriesClick) forControlEvents:UIControlEventTouchUpInside];
    
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_tableView.mas_bottom).offset(30);
        make.left.equalTo(self.view.mas_left).offset(10);
        make.right.equalTo(self.view.mas_right).offset(-10);
        make.height.equalTo(@40);
    }];
    
    UIButton * addButton = [[UIButton alloc]init];
    [addButton setTitle:@"添加" forState:UIControlStateNormal];
    [addButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [addButton setBackgroundColor:[UIColor colorWithRed:1 green:0.5 blue:0.6 alpha:1]];
    addButton.layer.cornerRadius = 10;
    addButton.layer.masksToBounds = YES;
    [_scroller addSubview:addButton];
    [addButton addTarget:self action:@selector(addClick) forControlEvents:UIControlEventTouchUpInside];
    
    [addButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(button.mas_bottom).offset(30);
        make.left.equalTo(self.view.mas_left).offset(10);
        make.right.equalTo(self.view.mas_right).offset(-10);
        make.height.equalTo(@40);
    }];
}


//添加按钮监听
-(void)addClick
{
    NSLog(@"路径 %@ ",NSHomeDirectory());
    
    UITextField * text0 = (id)[self.view viewWithTag:201];
    UITextField * text1 = (id)[self.view viewWithTag:202];
    UITextField * text2 = (id)[self.view viewWithTag:203];
    UITextField * text3 = (id)[self.view viewWithTag:204];
    UITextField * text4 = (id)[self.view viewWithTag:205];
    UIButton * button = (id)[self.view viewWithTag:100];
    
    if (text1.text.length == 0 || text2.text.length == 0 || text3.text.length == 0 || button.currentTitle.length == 0) {
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:nil message:@"请输入完整信息" delegate:self cancelButtonTitle:@"好的" otherButtonTitles: nil];
        [alert show];
        return;
    }
    
    NSArray * array = [Car MR_findAll];
    if (array.count == 0) {
        
        Car * car = [Car MR_createEntity];
        car.type = button.currentTitle;
        car.carsystem = text0.text;
        car.city = text1.text;
        car.carnumber = text2.text;
        car.enjinenumber = text3.text;
        car.remarks = text4.text;
        
        [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
    }
    
    for (Car * car in array) {
        
        if ([text2.text isEqualToString:car.carnumber]) {
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:@"该车牌号已存在,请重新输入" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alert show];
            return;

        }
        
        Car * car = [Car MR_createEntity];
        car.type = button.currentTitle;
        car.carsystem = text0.text;
        car.city = text1.text;
        car.carnumber = text2.text;
        car.enjinenumber = text3.text;
        car.remarks = text4.text;
        
        [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
        
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:nil message:@"添加成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        return;
    }
}

//查询按钮监听
-(void)equiriesClick
{
    UITextField * text1 = (id)[self.view viewWithTag:202];
    UITextField * text2 = (id)[self.view viewWithTag:203];
    UITextField * text3 = (id)[self.view viewWithTag:204];
    UIButton * button = (id)[self.view viewWithTag:100];
    
    if (text1.text.length == 0 || text2.text.length == 0 || text3.text.length == 0 || button.currentTitle.length == 0) {
        UIAlertView * alert = [[UIAlertView alloc]initWithTitle:nil message:@"请输入完整信息" delegate:self cancelButtonTitle:@"好的" otherButtonTitles: nil];
        [alert show];
        return;
    }
    
    NSArray * array = [Car MR_findAll];
    
    for (Car * car in array) {
        if ([button.currentTitle isEqualToString:car.type]) {
            if (![text1.text isEqualToString:car.city]) {
                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:@"该城市不存在,请重新输入" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                [alert show];
                return;
            }
            
            if (![text2.text isEqualToString:car.carnumber]) {
                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:@"该车牌不存在,请重新输入" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                [alert show];
                return;
            }
            
            if (![text3.text isEqualToString:car.enjinenumber]) {
                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:@"所填写发动机错误,请重新输入" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                [alert show];
                return;
            }
            
            showMessageVC * vc = [[showMessageVC alloc]init];
            UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:vc];
            [self presentViewController:nav animated:YES completion:nil];
            return;
        }else{
            count++;
        }
    }
    
    if (count == array.count) {
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:@"该车型不存在,请重新选择" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        return;
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 6;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{

    return 20;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray * textArray = @[@"",@"请选择车系(选填)",@"请选择城市",@"请输入车牌号",@"请输入全部的发动机号",@"请输入爱车昵称(选填)"];
    NSArray * titleArray = @[@"号牌类型",@"车 系",@"查询城市",@"车牌号码",@"发动机号",@"备注"];
    NSArray * imageName = @[@"publish_ask",@"jiantou2.png",@"jiantou2.png",@"",@"publish_ask",@""];
    TableViewCell * oneCell = [_tableView dequeueReusableCellWithIdentifier:@"oneCell"];
    AddCarTwocell * twoCell = [_tableView dequeueReusableCellWithIdentifier:@"twoCell"];
    addCarThreeCell * threeCell = [_tableView dequeueReusableCellWithIdentifier:@"threeCell"];
    if (!oneCell) {
        oneCell = [[[NSBundle mainBundle]loadNibNamed:@"TableViewCell" owner:nil options:nil]lastObject];
    }
    if (!twoCell) {
        twoCell = [[[NSBundle mainBundle]loadNibNamed:@"AddCarTwocell" owner:nil options:nil]lastObject];
    }
    if (!threeCell) {
        threeCell = [[[NSBundle mainBundle]loadNibNamed:@"addCarThreeCell" owner:nil options:nil]lastObject];
    }
    if (indexPath.section == 0) {
        //车型
        threeCell.carType.tag = 100;
        threeCell.imageButton.tag = indexPath.section;
        [threeCell.carType addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [threeCell.imageButton addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        threeCell.titleLabel.text = titleArray[indexPath.section];
        return threeCell;
    }else if (indexPath.section == 3 || indexPath.section == 5)
    {
        //车牌,备注
        twoCell.titleLabel.text = titleArray[indexPath.section];
        twoCell.textField.placeholder = textArray[indexPath.section];
        twoCell.textField.tag = 200+indexPath.section;
        twoCell.textField.delegate = self;
        return twoCell;
    }else{
        //车系,城市,车牌号码
        oneCell.titleLabel.text = titleArray[indexPath.section];
        [oneCell.rightButton setBackgroundImage:[UIImage imageNamed:imageName[indexPath.section]] forState:UIControlStateNormal];
        oneCell.rightButton.tag = indexPath.section;
        [oneCell.rightButton addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        oneCell.textField.placeholder = textArray[indexPath.section];
        oneCell.textField.tag = 200+indexPath.section;
        oneCell.textField.delegate = self;
        return oneCell;
    }
}

///点击键盘return的时候，执行
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    NSLog(@"点击键盘return的时候执行");
    if (textField.tag == 201 || textField.tag == 202 || textField.tag == 203 || textField.tag == 204 || textField.tag == 205 ) {
        //失去第一响应，收回第一键盘
        [textField resignFirstResponder];
    }
    
    return YES;//返回 yes 和 no 是一样的
}

//监听cell上的button
-(void)btnClick:(UIButton*)button
{
    switch (button.tag) {
        case 0:
        {
            //号牌类型
            a = 3;
            [self createLookView];
        }
            break;
        case 1:
        {
            //车系
        }
            break;
        case 2:
        {
            //查询城市
            CityVC * vc = [[CityVC alloc]init];
            UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:vc];
            vc.delegate = self;
            add = 1;
            [self presentViewController:nav animated:YES completion:nil];
        }
            break;
        case 4:
        {
            //发动机号
            a = 4;
            [self createLookView];
        }
            break;
        case 100:
        {
            //选择车类型
            _myitem = 0;
            [self createShowView];
            
        }
            break;
        default:
            break;
    }
}

//代理传值获取城市名
-(void)sendString:(NSString *)string andId:(NSNumber *)cid
{
    _cityName = string;
}

-(void)sendString:(NSString *)string
{
    
}

//弹出视图获取图片
-(void)createLookView
{
    LookShowView  = [[SucShowView alloc] initWithFrame:CGRectMake(100, 200, 200, 160)];
    LookShowView.delegate = self;
    [LookShowView looklookView];
}

-(void)disappear
{
    [LookShowView disappearView];
}

//弹出视图,获取车型
-(void)createShowView
{
    _showView = [[ShowView alloc]initWithFrame:CGRectMake(100, 130, 150, 80)];
    _showView.delegate = self;
    [_showView looklookView];
}

-(void)viewDisappear:(NSString *)carType
{
    UIButton * button = (id)[self.view viewWithTag:100];
    [button setTitle:carType forState:UIControlStateNormal];
    [_showView disappearView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end
